package org.wanho.sms.service.impl;

import java.util.List;

import org.wanho.sms.dao.StudentDao;
import org.wanho.sms.entity.Student;
import org.wanho.sms.exception.StudentNameExistsException;
import org.wanho.sms.exception.StudentNotFoundException;
import org.wanho.sms.factory.ObjectFactory;
import org.wanho.sms.service.StudentService;

public class StudentServiceImpl implements StudentService{

	private StudentDao studentDao = (StudentDao) ObjectFactory.getObject("studentDao");
	
	@Override
	public List<Student> findAll() {
		return studentDao.selectAll();
	}

	@Override
	public Student findById(int id) {
		return studentDao.selectById(id);
	}

	@Override
	public void modify(Student stu) {
		studentDao.update(stu);
	}

	@Override
	public void add(Student stu) throws StudentNameExistsException {
		// 先判断用户名是否已存在
		Student s = studentDao.selectByName(stu.getName());
		if(s != null){
			throw new StudentNameExistsException("用户名已存在！");
		}
		
		// 添加学生
		studentDao.insert(stu);
	}

	@Override
	public void removeById(int id) {
		studentDao.deleteById(id);
	}

	// 调换两名学生的班级
	@Override
	public void swap(String name1, String name2) throws StudentNotFoundException {
		Student stu1 = studentDao.selectByName(name1);
		Student stu2 = studentDao.selectByName(name2);
		if(stu1 == null){
			throw new StudentNotFoundException("未找到学生："+name1);
		}
		if(stu2 == null){
			throw new StudentNotFoundException("未找到学生："+name2);
		}
		
		studentDao.updateClazzId(stu1.getId(), stu2.getClazz().getId());
		// int i = 5/0;
		studentDao.updateClazzId(stu2.getId(), stu1.getClazz().getId());
	}

}
